﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using PurchaseOrderExtra;
using MyException;

namespace PresentationLayer
{
    public partial class RaisePurchaseOrder : System.Web.UI.Page
    {
        RaisePurchaseOrderControl control;
        User user;

        string supplierId;
        string supplierName;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Check if user exists and has permission to view this page
                if (Session["UserLoggedIn"] != null)
                {
                    List<string> list = Session["UserLoggedIn"] as List<string>;
                    if (list[0].Equals("validuser"))
                    {
                        int roleId = Convert.ToInt32(list[6]);
                        if (roleId != 5)
                        {
                            Response.Redirect("/AccessDenied.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("/Login.aspx");
                }
                #endregion

                control = new RaisePurchaseOrderControl();

                List<string> userList = Session["UserLoggedIn"] as List<string>;
                string username = userList[3];
                user = control.GetUserByUsername(username);

                List<string> poInfo = Session["SelectedRaisePO"] as List<string>;

                if (poInfo == null || poInfo.Count <= 0)
                {
                    ClearAllFields();
                    lblMessage.Text = "No purchase has been selected";
                }
                else
                {
                    supplierId = poInfo[0];
                    supplierName = poInfo[1];

                    lblSupplierName.Text = supplierName;

                    if (!IsPostBack)
                    {
                        // Populate dropdownlist
                        PopulateAttn();
                        GenerateGridView(user);
                    }
                }

                // Block the button to prevent multiple clicks by the user
                btnSubmit.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnSubmit).ToString() + ";");
            }
            catch (Exception ex)
            {
                // Release block button
                btnSubmit.Enabled = true;
            }
        }

        protected void ibtnExpectedDate_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                CalendarExpectedDate.Visible = true;
            }
            catch (Exception ex)
            {
            }
        }

        protected void CalendarExpectedDate_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                txtExpectedDate.Text = CalendarExpectedDate.SelectedDate.ToShortDateString();
                CalendarExpectedDate.SelectedDates.Clear();
                CalendarExpectedDate.Visible = false;
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            try
            {
                GenerateGridView(user);
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                CalendarExpectedDate.Visible = false;

                // to update TempPOItem and PO and PODetail table
                List<int> tempPOIdList = new List<int>();
                for (int i = 0; i < gvPurchaseOrder.Rows.Count; i++)
                {
                    Label tempPOIdGV = gvPurchaseOrder.Rows[i].FindControl("lblTempPOId") as Label;
                    int tempPOId = Convert.ToInt32(tempPOIdGV.Text);
                    tempPOIdList.Add(tempPOId);
                }
                int attnId = Convert.ToInt32(ddlAttn.SelectedValue);
                DateTime expectedDate = Convert.ToDateTime(txtExpectedDate.Text);
                if (expectedDate < DateTime.Today)
                {
                    throw new ExpectedDeliveryDateBeforeTodayException();
                }

                // Block button
                btnSubmit.Enabled = false;

                control.DeleteTempPOAndCreatePurchaseOrder(user, attnId, expectedDate, tempPOIdList);

                GenerateGridView(user);
                lblMessage.Text = "Purchase order has been submitted successfully";
                Session.Remove("SelectedRaisePO");

                // Release blocked button
                btnSubmit.Enabled = true;
            }
            catch (FormatException ex)
            {
                // Continue form validation
                btnSubmit.Enabled = true;
            }
            catch (ExpectedDeliveryDateBeforeTodayException ex)
            {
                btnSubmit.Enabled = true;
                ResetLabelsExceptTotal();
                lblDateError.Text = "*";
                lblMessage.Text = "* Date cannot be before today";
            }
            catch (Exception ex)
            {
                btnSubmit.Enabled = true;
            }
        }

        protected void btnSelectMore_Click(object sender, EventArgs e)
        {
            try
            {
                Session.Remove("SelectedRaisePO");
                string redirectURL = control.RedirectToSelectMoreItemsForPurchasing();
                Response.Redirect(redirectURL);
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnReturnToList_Click(object sender, EventArgs e)
        {
            try
            {
                Session.Remove("SelectedRaisePO");
                string redirectURL = control.RedirectToRaisePurchaseOrderList();
                Response.Redirect(redirectURL);
            }
            catch (Exception ex)
            {
            }
        }

        #region Populate Dropdownlist and GridView
        private void PopulateAttn()
        {
            List<Employee> list = control.DisplayAllStoreClerk();
            ddlAttn.DataSource = list;
            ddlAttn.DataTextField = "EmployeeName";
            ddlAttn.DataValueField = "EmployeeID";
            ddlAttn.DataBind();
        }

        private void GenerateGridView(User user)
        {
            ResetAllLabels();

            List<TempPurchaseOrderDisplay> list = new List<TempPurchaseOrderDisplay>();
            list = control.GetTempPOItemByClerkIdAndSupplierId(user, supplierId);
            if (list.Count <= 0)
            {
                ClearAllFields();
                lblMessage.Text = "There is no purchase order saved for this supplier";
            }
            else
            {
                decimal total = 0;
                foreach (TempPurchaseOrderDisplay poDisplay in list)
                {
                    total = total + poDisplay.Amount;
                }
                btnSubmit.Visible = true;
                lblTotal.Text = "Total: S$" + total;
            }
            gvPurchaseOrder.DataSource = list;
            gvPurchaseOrder.DataBind();
        }
        #endregion

        #region GridView Functions
        protected void gvPurchaseOrder_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                gvPurchaseOrder.EditIndex = e.NewEditIndex;
                GenerateGridView(user);
            }
            catch (Exception ex)
            {
            }
        }

        protected void gvPurchaseOrder_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                gvPurchaseOrder.EditIndex = -1;
                GenerateGridView(user);
            }
            catch (Exception ex)
            {
            }
        }

        protected void gvPurchaseOrder_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                // Save changes to tempPOITem table
                Label tempPOIdGV = gvPurchaseOrder.Rows[e.RowIndex].FindControl("lblTempPOId") as Label;
                TextBox quantityGV = gvPurchaseOrder.Rows[e.RowIndex].FindControl("txtQuantity") as TextBox;
                int tempPOId = Convert.ToInt32(tempPOIdGV.Text);
                int quantity = Convert.ToInt32(quantityGV.Text);
                control.UpdateTempPOItem(tempPOId, quantity);

                // Re-generate GridView
                gvPurchaseOrder.EditIndex = -1;
                GenerateGridView(user);
            }
            catch (Exception ex)
            {
            }
        }

        protected void gvPurchaseOrder_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                // delete row from tempPOITem table
                Label tempPOIdGV = gvPurchaseOrder.Rows[e.RowIndex].FindControl("lblTempPOId") as Label;
                int tempPOId = Convert.ToInt32(tempPOIdGV.Text);
                control.DeleteTempPOItem(tempPOId);

                // Re-generate GridView
                GenerateGridView(user);
            }
            catch (Exception ex)
            {
            }
        }
        #endregion

        private void ResetAllLabels()
        {
            ResetLabelsExceptTotal();
            lblTotal.Text = "";
        }

        private void ResetLabelsExceptTotal()
        {
            lblDateError.Text = "";
            lblMessage.Text = "";
        }

        private void ClearAllFields()
        {
            lblTotal.Text = "";
            lblMessage.Text = "";
            lblSupplierNameLabel.Text = "";
            lblSupplierName.Text = "";
            lblAttn.Text = "";
            ddlAttn.Visible = false;
            lblExpectedDate.Text = "";
            txtExpectedDate.Visible = false;
            ibtnExpectedDate.Visible = false;
            lblDateError.Text = "";
            CalendarExpectedDate.Visible = false;
            gvPurchaseOrder.Visible = false;
            btnSubmit.Visible = false;
        }

    }
}